import { TFunction } from 'i18next';

import { AppChatConfigType } from '@/types/app/type';
import {
  FlowNodeOutputTypeEnum,
  FlowNodeTemplateTypeEnum,
  FlowNodeTypeEnum,
  VARIABLE_NODE_ID,
  WorkflowIOValueTypeEnum,
} from '@/types/workflow/constant';
import { FlowNodeItemType, FlowNodeTemplateType } from '@/types/workflow/node';
import { getHandleConfig } from '@/types/workflow/template/utils';

import { getWorkflowGlobalVariables } from './utils';

export const getGlobalVariableNode = ({
  nodes,
  chatConfig,
  t,
}: {
  nodes: FlowNodeItemType[];
  chatConfig: AppChatConfigType;
  t: TFunction;
}) => {
  const template: FlowNodeTemplateType = {
    id: FlowNodeTypeEnum.globalVariable,
    templateType: FlowNodeTemplateTypeEnum.other,
    flowNodeType: FlowNodeTypeEnum.emptyNode,
    sourceHandle: getHandleConfig(false, false, false, false),
    targetHandle: getHandleConfig(false, false, false, false),
    avatar: 'variable.svg',
    name: t('common:core.module.Variable'),
    intro: '',
    unique: true,
    forbidDelete: true,
    version: '481',
    inputs: [],
    outputs: [],
  };

  const globalVariables = getWorkflowGlobalVariables({ nodes, chatConfig });

  const variableNode: FlowNodeItemType = {
    nodeId: VARIABLE_NODE_ID,
    ...template,
    outputs: globalVariables.map((item) => ({
      id: item.key,
      type: FlowNodeOutputTypeEnum.static,
      label: item.label,
      key: item.key,
      valueType: item.valueType || WorkflowIOValueTypeEnum.any,
    })),
  };

  return variableNode;
};
